﻿using System;
using MiniStock.Entities.Common.Events;
using MiniStock.Infrastructure;

namespace MiniStock.BusinessLogic.EventProcessor.EventRepository
{
    public static class IEventRepositoryExtender
    {
        public static EventBase Add<T2>(this T2 repository, EventBase item)
            where T2 : IRepository<EventProcessorEventData>
        {
            string entityId = null;

            if(item is EntityEventBase) entityId = ((EntityEventBase) item).GetEntityHash();
            else if(item is Snapshot) entityId = ((Snapshot) item).Entity.GetEntityHash();
            else throw new ApplicationException("Protocol events should not be saved to repository");

            repository.Add(new EventProcessorEventData
                         {
                             Id = item.EventId,
                             EntityId = entityId,
                             EventDate = DateTime.UtcNow,
                             ContentXml = item.ToXmlString(),
                             EventType = item.GetType().Name,
                         });

            return item;
        }


    }
}
